package com.yshkj.payment.utils;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对列表进行分组工具类
 * Created by 唐旭 on 2016/1/26.
 */
public abstract class GroupHelper {

    private GroupHelper() {
    }

    /**
     * 对列表进行分组
     *
     * @param keyField 分组的键,支持Object.field.subfield的写法
     * @param lists    需要分组的集合
     * @param <T>      集合中数据的类型
     * @return 分组结果Map＜Object, List＜T＞＞
     */
    public static <T> Map<Object, List<T>> groupByKey(String keyField, List<T> lists) {
        Map<Object, List<T>> listMap = new HashMap<>();

        try {
            for (T item : lists) {
                Field field = ReflectionUtils.findField(item.getClass(), keyField);
                field.setAccessible(true);
                Object temp = field.get(item);
                List<T> ts = listMap.get(temp);
                if (ts == null) {
                    ts = new ArrayList<>();
                }
                ts.add(item);
                if (!listMap.keySet().contains(temp)) {
                    listMap.put(temp, ts);
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return listMap;
    }

    public static Map<Object, List<Object>> groupByKey(List<GroupKey> lists) {
        Map<Object, List<Object>> listMap = new HashMap<>();

        for (GroupKey item : lists) {
            Object temp = item.getKey();
            List<Object> ts = listMap.get(temp);
            if (ts == null) {
                ts = new ArrayList<>();
            }
            ts.add(item);
            if (!listMap.keySet().contains(temp)) {
                listMap.put(temp, ts);
            }
        }
        return listMap;
    }

    @FunctionalInterface
    public interface GroupKey {
        Object getKey();
    }
}
